package com.sky.service.impl;

import com.sky.annotation.AutoFill;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
    @Transactional// 事务控制
    public void saveWithFlavors(DishDTO dishDTO) {
//        向菜品插入一条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.save(dish);

        Long id = dish.getId();//获取insert语句的主键id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!= null && flavors.size() > 0) {
            //向口味插入多条数据
//            for (DishFlavor flavor : flavors) {
//                flavor.setDishId(dish.getId());
//            }
            flavors.forEach(flavor -> {
                flavor.setDishId(id);
            });// 给每个口味设置菜品id
            dishFlavorMapper.insertBatch(flavors);
        }

    }
}

